/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.device.servlet;

import cn.net.greenet.common.db_service.HibernateBaseDao;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiendpointbean;
import cn.net.greenet.db.bean.Messageincominglog;
import cn.net.greenet.device.logic.ByteConvert;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * 获取指定设备动态信息
 *
 * @author LiuShang
 */
@WebServlet(name = "cn.net.greenet.device.servlet.GetDevDynamicInfo", urlPatterns = {"/device/information/device_dynamic"})
public class GetDevDynamicInfo extends HttpServlet {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");//设备ID

        Messageincominglog bean = null;
        PrintWriter out = response.getWriter();

        if (id != null && id.matches("[0-9]*")) {
            SessionFactory sf = HibernateUtil.getSessionFactory();
            Session session = sf.openSession();
            HibernateBaseDao hibernateBaseDao = new HibernateBaseDao();
            String hql = "SELECT log From Messageincominglog AS log WHERE log.messageType=:messageType AND log.dpiendpointbean.id=" + id + " ORDER BY log.time DESC";
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("messageType", "0xC6");

                java.util.List MessageInComingLogList = hibernateBaseDao.getListLimit(hql, 1, params, session);

                Dpiendpointbean dpi = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));

            String heartBeatHql = "SELECT log From Messageincominglog AS log WHERE log.messageType=:messageType AND log.dpiendpointbean.id=" + id + " ORDER BY log.time DESC";
            Map<String, Object> heartBeatParams = new HashMap<String, Object>();
            heartBeatParams.put("messageType", "0xC1");
            java.util.List heartBeatList = hibernateBaseDao.getListLimit(heartBeatHql, 1, heartBeatParams, session);

            JSONObject ddObject = new JSONObject();

            if (heartBeatList.isEmpty()) {
                ddObject.put("device_status", "未响应");
                ddObject.put("lastHeartBeatTime", "最近五分钟内未收到心跳包");
            } else {
                Messageincominglog heartBeatLog = (Messageincominglog) heartBeatList.get(0);
                System.out.println("current time:" + format.format(new Date(System.currentTimeMillis())) + "\t LastHeartBeat:" + format.format(heartBeatLog.getTime()));
                if ((System.currentTimeMillis() - heartBeatLog.getTime().getTime()) > 300000) {
                    ddObject.put("device_status", "未响应");
                    ddObject.put("lastHeartBeatTime", "最近五分钟内未收到心跳包");
                } else {
                    ddObject.put("device_status", "正常");
                    ddObject.put("lastHeartBeatTime", format.format(heartBeatLog.getTime()));
                }
            }

            ddObject.put("isServerChannelConnected", dpi.isIsServerChannelConnected() ? "1" : "0");
            ddObject.put("isClientChannelConnected", dpi.isIsClientChannelConnected() ? "1" : "0");

            if (MessageInComingLogList.size()<1 || !dpi.isEnabled()) {

                JSONArray Total_PortsArray = new JSONArray();
                JSONArray Total_CPUArray = new JSONArray();
                ddObject.put("Total_Ports", Total_PortsArray);
                ddObject.put("Total_CPU", Total_CPUArray);
                out.println(ddObject);
            } else if(MessageInComingLogList.size()>0 || dpi.isEnabled()) {
                bean = (Messageincominglog) MessageInComingLogList.get(0);
                System.out.println("动态-time-:" + bean.getTime());
                byte[] msg = bean.getPacket();
                int ptr = 18;
                int Total_PostNum = ByteConvert.bytesToUbyte(new byte[]{msg[ptr]});//本DPI设备的总端口数
                ptr++;

                JSONArray Total_PortsArray = new JSONArray();
                for (int i = 0; i < Total_PostNum; i++) {
                    JSONObject Total_PortsObject = new JSONObject();
                    byte PortNo = msg[ptr];//端口编号
                    ptr++;
                    Total_PortsObject.put("PortNo", ByteConvert.bytesToUbyte(new byte[]{PortNo}) + "");

                    int PortInfoLength = msg[ptr]&0xff;//端口描述信息长度
                    ptr++;
                    String PortInfo = new String(Arrays.copyOfRange(msg, ptr, ptr + PortInfoLength));//端口描述信息
                    ptr = ptr + PortInfoLength;
                    Total_PortsObject.put("PortInfo", PortInfo + "");

                    int PortUsage = msg[ptr]&0xff;//本端口利用率
                    ptr++;
                    Total_PortsObject.put("PortUsage", PortUsage + "");
                    Total_PortsArray.add(Total_PortsObject);
                }
                int Total_CPU_Num = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//本DPI设备中所含的CPU数
                ptr = ptr + 2;
                JSONArray Total_CPUArray = new JSONArray();
                for (int i = 0; i < Total_CPU_Num; i++) {
                    JSONObject Total_CPUObject = new JSONObject();
                    int CPU_No = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//CPU编号
                    ptr = ptr + 2;
                    Total_CPUObject.put("CPU_No", CPU_No + "");

                    byte CPU_Usage = msg[ptr];//本CPU利用率
                    ptr++;
                    Total_CPUObject.put("CPU_Usage", ByteConvert.bytesToUbyte(new byte[]{CPU_Usage}) + "");
                    System.out.println(Total_CPUObject);
                    Total_CPUArray.add(Total_CPUObject);
                }
                ddObject.put("Total_Ports", Total_PortsArray);
                ddObject.put("Total_CPU", Total_CPUArray);
                out.println(ddObject);
            }
//session.clear();
            /* TODO output your page here. You may use following sample code. */
            session.close();
        } else {
            out.println("[" + id + "]");
        }
        out.close();
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
